<?php

namespace App\Jobs\QiPao\Gift;

use App\Exceptions\BasicException;
use App\Jobs\Job;
use App\Models\ActivityDB\Love5202022GiftRank;
use App\Models\ActivityDB\Love5202022Setting;
use App\Services\Tools\IdempotentConsume;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class Gift520Job extends Job
{
    protected $data;
    const jobName = 'Gift520Job';

    public function __construct($data)
    {
        $this->data = $data;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        if(env('APP_ENV') != 'production'){
            Log::error('Gift520:' . json_encode(['time' => getMillisecond(), 'data' => $this->data]));
        }
        try {

            $Love520SettingModel = new Love5202022Setting();
            $is_open = $Love520SettingModel->isOpen();
            $idempotentConsumeServer =  new IdempotentConsume();
            $data = $this->data;
            $uk = $data['id']??'';
            if($is_open && $idempotentConsumeServer->checkIdempotentRedisKey(self::jobName,$uk)){
                $giveGifts = app('model_give_gift')->newQuery()
                    ->whereIn('id',$this->data)->select(['user_id','gift_id','gift_user','total_price'])
                    ->get();
                    DB::beginTransaction();
                    try{
                        //520活动期间记录一次性
                        foreach ($giveGifts as $item){
                            if ($Love520SettingModel->isInAct($item->gift_id)){
                                Log::info('Gift520:' . json_encode(['time' => time(), 'data' => $item->gift_id]));
                                (new Love5202022GiftRank())->add($item);
                            }
                        }
                        DB::commit();
                    }catch (\Exception $e){
                        DB::rollBack();
                        throw new BasicException($e->getCode(),  $e->getMessage());
                    }

            }

        } catch (\Exception $exception) {
            $idempotentConsumeServer->deleteIdempotentRedisKey(self::jobName,$data['id']);
            Log::error('GiftWallJob:'.$exception->getMessage());
        }
    }

}
